import { userlogin, logout, getInfo } from '@/api/user'
import request from '@/utils/request'
import { getToken, setToken, removeToken } from '@/utils/auth'
import router, { resetRouter } from '@/router'
import axios from 'axios'

const state = {
  token: getToken(),
  name: '',
  avatar: '',
  introduction: '',
  roles: []
}

const mutations = {
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_INTRODUCTION: (state, introduction) => {
    state.introduction = introduction
  },
  SET_NAME: (state, name) => {
    state.name = name
  },
  SET_AVATAR: (state, avatar) => {
    state.avatar = avatar
  },
  SET_ROLES: (state, roles) => {
    state.roles = roles
  }
}

const actions = {
  // user login
  userlogin({ commit }, userInfo) {
    // login({ username: username.trim(), password: password })
    const { username, password } = userInfo
    return new Promise((resolve, reject) => {
      // axios.post("http://60.205.188.102:16036/user/login",{
      //   userName: username,
      //   userPassword: password
      // })
      request({
        url: '/user/login',
        method: 'post',
        data: {
          userName: username,
          userPassword: password
        }
      })
      // userlogin({ userName: username, userPassword: password })
      .then(response => {
        console.log(response.data)
        if (response.data.code == 200) {
          sessionStorage.setItem("user", JSON.stringify(response.data.data))
          const { data } = response
          data.token = 'editor-token'
          commit('SET_TOKEN', data.token)
          setToken(data.token)
          resolve()
        }else{
          alert(response.data.message)
          reject(error)
        }
      }).catch(error => {
        reject(error)
      })
    })
  },

  // store login
  storelogin({ commit }, storeInfo) {
    const { username, password } = storeInfo
    return new Promise((resolve, reject) => {
      // login({ username: username.trim(), password: password })
      // axios.post("http://60.205.188.102:16036/store/login",{
        request.post("/store/login",{
        storeName: username,
        password: password
      }).then(response => {
        if (response.data.code == 200){
          sessionStorage.setItem("store", JSON.stringify(response.data.data))
          const { data } = response
          //  set token
          data.token = 'admin-token'
          commit('SET_TOKEN', data.token)
          setToken(data.token)
          resolve()
        } else {
          alert(response.data.message)
          reject(error)
        }

      }).catch(error => {
        console.log(error)
        reject(error)
      })
    })
  },

  // get user info
  getInfo({ commit, state }) {
    return new Promise((resolve, reject) => {
      commit('SET_TOKEN', getToken())

      getInfo(state.token).then(response => {
        const { data } = response.data
        // console.log(getToken())
        // console.log(response)
        if (!data) {
          reject('Verification failed, please Login again.')
        }

        const { roles, name, avatar, introduction } = data

        // roles must be a non-empty array
        if (!roles || roles.length <= 0) {
          reject('getInfo: roles must be a non-null array!')
        }
        if(state.token == 'admin-token') {
          data.roles = ['store']
          // data.name=JSON.parse(sessionStorage.getItem('login_name'))
          // data.name = JSON.parse(sessionStorage.getItem('store')).storeName
        }
        else {
          data.roles = ['customer']
          data.name=JSON.parse(sessionStorage.getItem('login_name'))
          // data.name = JSON.parse(sessionStorage.getItem('user')).userName
        }
        // console.log(state.token)
        // console.log(roles)
        commit('SET_ROLES', data.roles)
        commit('SET_NAME', name)
        commit('SET_AVATAR', avatar)
        commit('SET_INTRODUCTION', introduction)
        resolve(data)
      }).catch(error => {
        reject(error)
      })
    })
  },

  // user logout
  logout({ commit, state, dispatch }) {
    return new Promise((resolve, reject) => {
      // logout(state.token).then(() => {
        commit('SET_TOKEN', '')
        commit('SET_ROLES', [])
        removeToken()
        resetRouter()
        alert('logout')
        // sessionStorage.removeItem('store')
        // sessionStorage.removeItem('user')
        // console.log('logout')
        sessionStorage.clear()

        // reset visited views and cached views
        // to fixed https://github.com/PanJiaChen/vue-element-admin/issues/2485
        dispatch('tagsView/delAllViews', null, { root: true })

        resolve()
      // }).catch(error => {
      //   reject(error)
      // })
    })
  },

  // remove token
  resetToken({ commit }) {
    return new Promise(resolve => {
      commit('SET_TOKEN', '')
      commit('SET_ROLES', [])
      removeToken()
      resolve()
    })
  },

  // dynamically modify permissions
  async changeRoles({ commit, dispatch }, role) {
    const token = role + '-token'

    commit('SET_TOKEN', token)
    setToken(token)

    const { roles } = await dispatch('getInfo')

    resetRouter()

    // generate accessible routes map based on roles
    const accessRoutes = await dispatch('permission/generateRoutes', roles, { root: true })
    // dynamically add accessible routes
    router.addRoutes(accessRoutes)

    // reset visited views and cached views
    dispatch('tagsView/delAllViews', null, { root: true })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
